package com.zhangmeng.tools.components;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-05-08 11:41
 */

import javafx.application.Platform;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.util.Callback;
import org.apache.commons.io.FilenameUtils;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.*;

public class RecursiveFileList extends TreeView<File> {

    private final SimpleObjectProperty<File> index_file = new SimpleObjectProperty<>(null);


    public RecursiveFileList(File root) {
        super(new TreeItem<>(root));
        if (root != null){
            new Thread(()->{
                Platform.runLater(()->{
                    setRoot(getTreeItem(root));
                });
            }).start();
        }else {
            setRoot(null);
        }
        setShowRoot(true);
        this.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue.getValue().isFile()) {
                index_file.setValue(newValue.getValue());
            }
        });
    }

    private TreeItem<File> getTreeItem(File file) {
        TreeItem<File> item = new TreeItem<>();
        item.setGraphic(new Text(file.getName()));
        item.setValue(file);
        if (file.isDirectory()) {
            if (file.listFiles()!= null){
                List<File> fileList = new ArrayList<>();
                File[] dirs = file.listFiles(File::isDirectory);
                if (dirs != null){
                    Arrays.sort(dirs, Comparator.comparing(File::getName));
                    fileList.addAll(List.of(dirs));
                }
                File[] files = file.listFiles(File::isFile);
                if (files != null){
                    Arrays.sort(files, Comparator.comparing(File::getName));
                    fileList.addAll(List.of(files));
                }
                for (File child : fileList) {
                    item.getChildren().add(getTreeItem(child));
                }
            }
        }
        return item;
    }

    public File getValue() {
        if (index_file.getValue() == null) {
           return null;
        }
        return index_file.getValue();
    }
}
